"""
评价模型
包含评价相关的类定义
"""

import uuid
from datetime import datetime
from typing import List, Optional
from core.utils.logger import debug, info, warning, error


class Review:
    """评价类 - 表示用户对商品的评价"""
    
    def __init__(self, review_id: str, product_id: str, user_id: str, 
                 order_id: str, rating: int, comment: str, 
                 images: List[str] = None, created_at: str = None, 
                 helpful_count: int = 0, user_name: str = ""):
        """
        初始化评价对象
        
        Args:
            review_id: 评价ID
            product_id: 商品ID
            user_id: 用户ID
            order_id: 订单ID（用于验证购买）
            rating: 评分（1-5）
            comment: 评论内容
            images: 图片路径列表
            created_at: 创建时间
            helpful_count: 有用数
            user_name: 用户名
        """
        self.review_id = review_id
        self.product_id = product_id
        self.user_id = user_id
        self.order_id = order_id
        self.rating = rating
        self.comment = comment or ""
        self.images = images or []
        self.created_at = created_at or datetime.now().isoformat()
        self.helpful_count = helpful_count
        self.user_name = user_name
        
        # 验证数据
        self._validate()
    
    def _validate(self):
        """验证评价数据"""
        if not self.review_id:
            raise ValueError("Review ID cannot be empty")
        
        if not self.product_id:
            raise ValueError("Product ID cannot be empty")
        
        if not self.user_id:
            raise ValueError("User ID cannot be empty")
        
        if not self.order_id:
            raise ValueError("Order ID cannot be empty")
        
        if not isinstance(self.rating, int) or self.rating < 1 or self.rating > 5:
            raise ValueError("Rating must be an integer between 1 and 5")
        
        if not isinstance(self.helpful_count, int) or self.helpful_count < 0:
            raise ValueError("Helpful count must be a non-negative integer")
    
    def get_rating_display(self) -> str:
        """获取评分的星号显示"""
        return "★" * self.rating + "☆" * (5 - self.rating)
    
    def get_rating_text(self) -> str:
        """获取评分的文字描述"""
        rating_texts = {
            1: "Poor",
            2: "Fair", 
            3: "Average",
            4: "Good",
            5: "Excellent"
        }
        return rating_texts.get(self.rating, "Unknown")
    
    def get_created_time_display(self) -> str:
        """获取格式化的创建时间"""
        try:
            dt = datetime.fromisoformat(self.created_at)
            return dt.strftime('%Y-%m-%d %H:%M')
        except:
            return self.created_at
    
    def add_helpful(self):
        """增加有用数"""
        self.helpful_count += 1
    
    def to_dict(self) -> dict:
        """转换为字典"""
        return {
            'review_id': self.review_id,
            'product_id': self.product_id,
            'user_id': self.user_id,
            'order_id': self.order_id,
            'rating': self.rating,
            'comment': self.comment,
            'images': self.images,
            'created_at': self.created_at,
            'helpful_count': self.helpful_count,
            'user_name': self.user_name
        }
    
    @classmethod
    def from_dict(cls, data: dict):
        """从字典创建评价对象"""
        return cls(
            review_id=data.get('review_id', ''),
            product_id=data.get('product_id', ''),
            user_id=data.get('user_id', ''),
            order_id=data.get('order_id', ''),
            rating=data.get('rating', 0),
            comment=data.get('comment', ''),
            images=data.get('images', []),
            created_at=data.get('created_at'),
            helpful_count=data.get('helpful_count', 0),
            user_name=data.get('user_name', '')
        )
    
    @classmethod
    def create_new(cls, product_id: str, user_id: str, order_id: str, 
                   rating: int, comment: str, user_name: str = "", 
                   images: List[str] = None) -> 'Review':
        """创建新评价"""
        review_id = f"REV-{uuid.uuid4().hex[:8].upper()}"
        return cls(
            review_id=review_id,
            product_id=product_id,
            user_id=user_id,
            order_id=order_id,
            rating=rating,
            comment=comment,
            user_name=user_name,
            images=images or []
        )
    
    def __repr__(self):
        return f"Review({self.review_id}, {self.product_id}, {self.rating}星, {self.user_name})"
